{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 字典的相关代码练习"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 认识字典的无序性 P95-P98"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'name': 'Ford Prefect',\n",
       " 'Gender': 'Male',\n",
       " 'Occupation': 'Researcher',\n",
       " 'Home Planet': 'Betelgeuse Seven'}"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "person3 = {'name':'Ford Prefect',\n",
    "           'Gender':'Male',\n",
    "           'Occupation':'Researcher',\n",
    "           'Home Planet':'Betelgeuse Seven'}\n",
    "person3\n",
    "##课本结论：列表会维持对象插入时的顺序，而字典不会维持插入顺序，是无序的。  \n",
    "##但是在jupyter中python的版本已经解决了字典的无序问题，所以此处代码运行结果是有序的。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 认识字典的中括号访问键值对p98"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Betelgeuse Seven'"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "person3['Home Planet']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Ford Prefect'"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "person3['name']"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 运行时处理字典（添加键-值对）P101"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'name': 'Ford Prefect',\n",
       " 'Gender': 'Male',\n",
       " 'Occupation': 'Researcher',\n",
       " 'Home Planet': 'Betelgeuse Seven',\n",
       " 'age': 33}"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "person3 = {'name':'Ford Prefect',\n",
    "           'Gender':'Male',\n",
    "           'Occupation':'Researcher',\n",
    "           'Home Planet':'Betelgeuse Seven'}\n",
    "person3['age']=33\n",
    "person3"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 创建空字典并统计元音字母个数的练习 p104  \n",
    "## （频度技数数据结构）\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{}"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "found ={}\n",
    "found #创建空字典"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'a': 0, 'e': 0, 'i': 0, 'o': 0, 'u': 0}"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "found['a'] = 0\n",
    "found['e'] = 0\n",
    "found['i'] = 0\n",
    "found['o'] = 0\n",
    "found['u'] = 0\n",
    "found ##设置元音的值初始化为0，字典的键必须初始化"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'a': 0, 'e': 1, 'i': 0, 'o': 0, 'u': 0}"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "found['e'] = found['e']+1\n",
    "found ##更新频度计数器"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'a': 0, 'e': 2, 'i': 0, 'o': 0, 'u': 0}"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "found['e']+= 1\n",
    "found ##更新频度2.0"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 迭代处理字典中的键和值"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a was found 0 time(s).\n",
      "e was found 2 time(s).\n",
      "i was found 0 time(s).\n",
      "o was found 0 time(s).\n",
      "u was found 0 time(s).\n"
     ]
    }
   ],
   "source": [
    "for k in found:\n",
    "        print(k,'was found',found[k],'time(s).')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a was found 0 time(s)\n",
      "e was found 2 time(s)\n",
      "i was found 0 time(s)\n",
      "o was found 0 time(s)\n",
      "u was found 0 time(s)\n"
     ]
    }
   ],
   "source": [
    "for k in sorted(found): ## sorted可以使字母按顺序输出\n",
    "    print(k,'was found',found[k],'time(s)')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a was found 0 time(s).\n",
      "e was found 2 time(s).\n",
      "i was found 0 time(s).\n",
      "o was found 0 time(s).\n",
      "u was found 0 time(s).\n"
     ]
    }
   ],
   "source": [
    "for k,v in sorted(found.items()):##用items迭代处理字典\n",
    "    print(k,'was found',v,'time(s).')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 避免运行时出现keyerror"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "fruits={}\n",
    "fruits['apples'] = 10\n",
    "fruits\n",
    "\n",
    "'apples' in fruits\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 用in检查某元素是否存在"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'apples': 10, 'bananas': 1}"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "if 'bananas'in fruits:  ##用bananas是否在fruits中\n",
    "    fruits['bananas']+= 1\n",
    "else:\n",
    "    fruits['bananas']=1\n",
    "fruits"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'apples': 10, 'bananas': 1, 'pears': 1}"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "if 'pears'not in fruits: ##用not in替换in，产生新元素\n",
    "    fruits['pears'] = 0\n",
    "fruits['pears']+= 1\n",
    "fruits"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'apples': 10, 'bananas': 1, 'pears': 2}"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "fruits.setdefault('pears',0) ##等价于上面的not in，也可以避免键不存在，没有初始化值而代码运行报错\n",
    "fruits['pears']+=1\n",
    "fruits"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Provide a word to search for vowels:please\n",
      "e\n",
      "a\n"
     ]
    }
   ],
   "source": [
    "vowels = ['a','e','i','o','u']\n",
    "word = input(\"Provide a word to search for vowels:\")\n",
    "found = []\n",
    "for letter in word:\n",
    "    if letter in vowels:\n",
    "        if letter not in found:\n",
    "            found.append(letter)\n",
    "for vowel in found:\n",
    "    print(vowel)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 集合的相关代码练习"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'a', 'e', 'i', 'o', 'u'}"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 认识了解集合不允许有重复元素,和字典一样不会维持插入顺序的特点\n",
    "vowels = {'a','e','e','i','o','u','u'}\n",
    "vowels"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Provide a word to search for vowels:good\n",
      "o\n"
     ]
    }
   ],
   "source": [
    "## 从序列创建集合\n",
    "vowel =['a','e','i','o','u']\n",
    "word = input(\"Provide a word to search for vowels:\")\n",
    "found=[]\n",
    "for letter in word:\n",
    "    if letter in vowels:\n",
    "        if letter not in found:\n",
    "            found.append(letter)\n",
    "for vowel in found:\n",
    "    print(vowel)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 充分利用集合方法\n",
    "vowels=set('aeiou')\n",
    "word='hello'\n",
    "u = vowels.union(set(word))## 用union方法创建新集合"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['a', 'e', 'h', 'i', 'l', 'o', 'u']"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "##union合并集合后转换为一个有序列表\n",
    "u_list = sorted(list(u))\n",
    "u_list\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'a', 'i', 'u'}"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "##利用difference方法找出两个集合的非共有元素\n",
    "d=vowels.difference(set(word))\n",
    "d"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'e', 'o'}"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "##利用intersection方法报告共同对象\n",
    "i=vowels.intersection(set(word))\n",
    "i"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Provide a word to search for vowels:happy\n",
      "a\n"
     ]
    }
   ],
   "source": [
    "##运行练习\n",
    "vowels=set('aeizou')\n",
    "word=input(\"Provide a word to search for vowels:\")\n",
    "found = vowels.intersection(set(word))\n",
    "for vowel in found:\n",
    "    print(vowel)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 元祖的相关代码练习"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "list"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "##如何发现代码中的元祖\n",
    "vowels = ['a','e','i','o','u']\n",
    "type(vowels)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tuple"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "##如何发现代码中的元祖 （续上）\n",
    "vowels2 = ('a','e','i','o','u')\n",
    "type(vowels2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['a', 'e', 'i', 'o', 'u']"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "vowels##运行结果是一个列表"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "('a', 'e', 'i', 'o', 'u')"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "vowels2 ##运行出小括号则表示这是一个元祖"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['a', 'e', 'I', 'o', 'u']"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "##认识了解元祖不可变的性质\n",
    "vowels[2]='I' ##将一个“I”赋值到vowels列表第三个元素\n",
    "vowels"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "ename": "TypeError",
     "evalue": "'tuple' object does not support item assignment",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mTypeError\u001b[0m                                 Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-16-50a011485511>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mvowels2\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;36m2\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m=\u001b[0m\u001b[1;34m'I'\u001b[0m \u001b[1;31m##运行会报错，因为元祖是不可变的。\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[1;31mTypeError\u001b[0m: 'tuple' object does not support item assignment"
     ]
    }
   ],
   "source": [
    "vowels2[2]='I' ##运行会报错，因为元祖是不可变的。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'python'"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#注意只有一个对象的元祖要在末尾加逗号“，”，否则会被识别为单个字符串而不是元祖。\n",
    "#只有一个对象的错误示范\n",
    "t = ('python')\n",
    "type(t)\n",
    "t"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'python,'"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#只有一个对象的元祖的正确示范\n",
    "t2=('python,')\n",
    "type(t2)\n",
    "t2 #解释器的运行结果：显示单个对象元祖会带末尾的逗号"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 字典的嵌套练习"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'Ford': {'Name': 'Ford Prefect',\n",
       "  'Gender': 'Male',\n",
       "  'Occupation': 'Researcher',\n",
       "  'Home Planet': 'Betelgeuse Seven'}}"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "people ={}\n",
    "people['Ford']={'Name':'Ford Prefect',\n",
    "                'Gender':'Male',\n",
    "                'Occupation':'Researcher',\n",
    "                'Home Planet':'Betelgeuse Seven'}  #键是“Ford”，值是另一个字典\n",
    "people              "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'Ford': {'Name': 'Ford Prefect',\n",
       "  'Gender': 'Male',\n",
       "  'Occupation': 'Researcher',\n",
       "  'Home Planet': 'Betelgeuse Seven'},\n",
       " 'Arthur': {'Name': 'Arthur Dent',\n",
       "  'Gender': 'Male',\n",
       "  'Occupation': ' Sandwich-Maker',\n",
       "  'Home Planet': 'Earth'},\n",
       " 'Trillian': {'Name': 'Tricia McMillan',\n",
       "  'Gender': ' Female',\n",
       "  'Occupation': ' Ma thematician ',\n",
       "  'Home Planet': 'Earth'},\n",
       " 'Robot': {'Name': 'Marvin',\n",
       "  'Gender': ' Unknown',\n",
       "  ' Occupation': ' Paranoid Android',\n",
       "  'Home Planet': 'Unknown'}}"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "people['Arthur'] = { 'Name': 'Arthur Dent',\n",
    "'Gender' : 'Male' ,\n",
    "'Occupation' : ' Sandwich-Maker',\n",
    "'Home Planet': 'Earth' }\n",
    "people['Trillian'] = { 'Name': 'Tricia McMillan',\n",
    "'Gender':' Female',\n",
    "'Occupation': ' Ma thematician ',\n",
    "'Home Planet': 'Earth' }\n",
    "people['Robot'] = { 'Name': 'Marvin',\n",
    "'Gender' : ' Unknown' ,\n",
    "' Occupation' : ' Paranoid Android',\n",
    "'Home Planet': 'Unknown', }\n",
    "\n",
    "people"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'Arthur': {'Gender': 'Male',\n",
      "            'Home Planet': 'Earth',\n",
      "            'Name': 'Arthur Dent',\n",
      "            'Occupation': ' Sandwich-Maker'},\n",
      " 'Ford': {'Gender': 'Male',\n",
      "          'Home Planet': 'Betelgeuse Seven',\n",
      "          'Name': 'Ford Prefect',\n",
      "          'Occupation': 'Researcher'},\n",
      " 'Robot': {' Occupation': ' Paranoid Android',\n",
      "           'Gender': ' Unknown',\n",
      "           'Home Planet': 'Unknown',\n",
      "           'Name': 'Marvin'},\n",
      " 'Trillian': {'Gender': ' Female',\n",
      "              'Home Planet': 'Earth',\n",
      "              'Name': 'Tricia McMillan',\n",
      "              'Occupation': ' Ma thematician '}}\n"
     ]
    }
   ],
   "source": [
    "##如何美观处理上述复杂的数据结构:调用pprint模块\n",
    "import pprint\n",
    "pprint.pprint(people)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'Name': 'Arthur Dent',\n",
       " 'Gender': 'Male',\n",
       " 'Occupation': ' Sandwich-Maker',\n",
       " 'Home Planet': 'Earth'}"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "##如何访问一个复杂的数据结构的数据\n",
    "people['Arthur'] #指定访问某行"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "' Sandwich-Maker'"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "people['Arthur']['Occupation']#指定访问某行某列"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
